/**
 * 音频管理 Store
 * 
 * 职责：
 * - 管理大厅背景音乐的播放/暂停
 * - 管理音效的播放状态
 * - 保存用户的音乐偏好设置
 */
import { defineStore } from 'pinia'
import { ref, computed } from 'vue'

export const useAudioStore = defineStore('audio', () => {
  // 音频状态
  const isMusicEnabled = ref(true)
  const isSoundEnabled = ref(true)
  const musicVolume = ref(0.5)
  const soundVolume = ref(0.7)
  const isPlaying = ref(false)
  
  // 音频元素引用
  let backgroundMusic = null
  let currentMusicSrc = ''
  
  // 自动播放管理器
  let autoPlayManager = null
  
  // 计算属性
  const musicIcon = computed(() => isMusicEnabled.value ? '🔊' : '🔇')
  const soundIcon = computed(() => isSoundEnabled.value ? '🔊' : '🔇')
  
  // 初始化音频
  const initAudio = () => {
    // 从本地存储恢复设置
    const savedMusicEnabled = localStorage.getItem('musicEnabled')
    const savedSoundEnabled = localStorage.getItem('soundEnabled')
    const savedMusicVolume = localStorage.getItem('musicVolume')
    const savedSoundVolume = localStorage.getItem('soundVolume')
    
    if (savedMusicEnabled !== null) {
      isMusicEnabled.value = JSON.parse(savedMusicEnabled)
    }
    if (savedSoundEnabled !== null) {
      isSoundEnabled.value = JSON.parse(savedSoundEnabled)
    }
    if (savedMusicVolume !== null) {
      musicVolume.value = parseFloat(savedMusicVolume)
    }
    if (savedSoundVolume !== null) {
      soundVolume.value = parseFloat(savedSoundVolume)
    }
    
    // 初始化自动播放管理器
    initAutoPlayManager()
    
    console.log('🎵 音频系统初始化完成:', {
      musicEnabled: isMusicEnabled.value,
      soundEnabled: isSoundEnabled.value,
      musicVolume: musicVolume.value,
      soundVolume: soundVolume.value
    })
  }
  
  // 初始化自动播放管理器
  const initAutoPlayManager = () => {
    if (autoPlayManager) return
    
    console.log('🎵 初始化自动播放管理器...')
    
    // 创建隐藏的音频元素用于测试自动播放能力
    const testAudio = new Audio()
    testAudio.muted = true
    testAudio.volume = 0
    
    // 测试自动播放能力
    const testAutoPlay = async () => {
      try {
        await testAudio.play()
        console.log('🎵 浏览器支持自动播放')
        return true
      } catch (error) {
        console.log('🎵 浏览器不支持自动播放:', error.name)
        return false
      }
    }
    
    // 执行测试
    testAutoPlay().then(supportsAutoPlay => {
      if (!supportsAutoPlay) {
        console.log('🎵 设置全局用户交互监听器...')
        setupGlobalInteractionListener()
        // 不再创建音乐播放按钮
      }
    })
  }
  
  // 更新音乐按钮状态（供外部调用）
  const updateMusicButtonState = () => {
    // 不再需要更新音乐按钮状态
    console.log('🎵 音乐状态已更新，当前状态:', isPlaying.value ? '播放中' : '已暂停')
  }
  
  // 设置全局用户交互监听器
  const setupGlobalInteractionListener = () => {
    const events = ['click', 'touchstart', 'keydown']
    let hasInteracted = false
    
    const handleInteraction = (event) => {
      if (hasInteracted) return
      
      console.log('🎵 检测到全局用户交互:', event.type, event.target)
      hasInteracted = true
      
      // 移除所有事件监听器
      events.forEach(eventType => {
        document.removeEventListener(eventType, handleInteraction)
      })
      
      // 如果有待播放的音乐，立即播放
      if (currentMusicSrc && !isPlaying.value) {
        console.log('🎵 播放待播放的音乐:', currentMusicSrc)
        // 延迟一点时间确保交互事件完全处理
        setTimeout(() => {
          playBackgroundMusic(currentMusicSrc).catch(error => {
            console.warn('🎵 全局交互后播放音乐失败:', error)
          })
        }, 100)
      }
    }
    
    events.forEach(eventType => {
      document.addEventListener(eventType, handleInteraction, { 
        passive: false,
        capture: true 
      })
    })
    
    // 设置超时清理
    setTimeout(() => {
      if (!hasInteracted) {
        console.log('🎵 清理全局交互监听器（超时）')
        events.forEach(eventType => {
          document.removeEventListener(eventType, handleInteraction)
        })
      }
    }, 60000) // 1分钟超时
  }
  
  // 播放大厅背景音乐
  const playBackgroundMusic = (musicSrc) => {
    return new Promise((resolve, reject) => {
      if (!isMusicEnabled.value || !musicSrc) {
        console.log('🎵 音乐播放条件不满足:', { isMusicEnabled: isMusicEnabled.value, musicSrc })
        reject(new Error('音乐播放条件不满足'))
        return
      }
      
      console.log('🎵 开始播放背景音乐:', musicSrc)
      
      // 如果已经有音乐在播放，先停止
      if (backgroundMusic) {
        backgroundMusic.pause()
        backgroundMusic = null
      }
      
      try {
        // 创建新的音频元素
        backgroundMusic = new Audio(musicSrc)
        backgroundMusic.loop = true
        backgroundMusic.volume = musicVolume.value
        backgroundMusic.preload = 'auto'
        
        // 设置音频属性
        backgroundMusic.crossOrigin = 'anonymous'
        
        // 添加音频事件监听器
        backgroundMusic.addEventListener('loadstart', () => console.log('🎵 音频开始加载'))
        backgroundMusic.addEventListener('canplay', () => console.log('🎵 音频可以播放'))
        backgroundMusic.addEventListener('playing', () => {
          console.log('🎵 音频开始播放')
          isPlaying.value = true
          // 使用淡入效果
          fadeInMusic()
          resolve()
        })
        backgroundMusic.addEventListener('pause', () => {
          console.log('🎵 音频已暂停')
          isPlaying.value = false
        })
        backgroundMusic.addEventListener('ended', () => {
          console.log('🎵 音频播放结束')
          isPlaying.value = false
        })
        backgroundMusic.addEventListener('error', (e) => {
          console.error('🎵 音频播放错误:', e)
          isPlaying.value = false
          reject(new Error('音频播放失败'))
        })
        
        // 直接尝试播放（用户已经交互过了）
        console.log('🎵 用户已交互，尝试播放音乐...')
        backgroundMusic.play()
          .then(() => {
            console.log('🎵 音乐播放成功!')
            currentMusicSrc = musicSrc
            isPlaying.value = true
            fadeInMusic()
            resolve()
          })
          .catch(error => {
            console.error('🎵 音乐播放失败:', error)
            reject(error)
          })
        
      } catch (error) {
        console.error('🎵 创建音频元素失败:', error)
        reject(error)
      }
    })
  }
  
  // 停止背景音乐
  const stopBackgroundMusic = () => {
    if (backgroundMusic) {
      backgroundMusic.pause()
      backgroundMusic = null
      currentMusicSrc = ''
      isPlaying.value = false
      console.log('🔇 背景音乐已停止')
    }
  }
  
  // 暂停背景音乐
  const pauseBackgroundMusic = () => {
    if (backgroundMusic) {
      backgroundMusic.pause()
      isPlaying.value = false
      console.log('⏸️ 背景音乐已暂停')
    }
  }
  
  // 恢复背景音乐
  const resumeBackgroundMusic = () => {
    if (backgroundMusic && isMusicEnabled.value) {
      backgroundMusic.play().catch(error => {
        console.warn('恢复背景音乐失败:', error)
        isPlaying.value = false
      })
      isPlaying.value = true
      console.log('▶️ 背景音乐已恢复')
    }
  }
  
  // 切换音乐开关
  const toggleMusic = async () => {
    const newState = !isMusicEnabled.value
    isMusicEnabled.value = newState
    
    try {
      if (newState) {
        // 开启音乐
        console.log('🎵 用户开启音乐')
        if (currentMusicSrc) {
          // 如果有之前的音乐源，立即恢复播放
          console.log('🎵 恢复播放之前的音乐:', currentMusicSrc)
          await playBackgroundMusic(currentMusicSrc)
        } else {
          // 如果没有音乐源，使用默认音乐
          const defaultMusicSrc = '/audio/大厅背景音乐.mp3'
          console.log('🎵 播放默认音乐:', defaultMusicSrc)
          await playBackgroundMusic(defaultMusicSrc)
        }
      } else {
        // 关闭音乐 - 使用淡出效果
        console.log('🎵 用户关闭音乐，淡出中...')
        fadeOutMusic()
      }
      
      // 保存设置到本地存储
      localStorage.setItem('musicEnabled', JSON.stringify(isMusicEnabled.value))
      console.log('🎵 音乐开关:', isMusicEnabled.value ? '开启' : '关闭')
      
      return Promise.resolve()
    } catch (error) {
      console.error('🎵 音乐切换失败:', error)
      // 如果失败，回滚状态
      isMusicEnabled.value = !newState
      return Promise.reject(error)
    }
  }
  
  // 淡出音乐效果
  const fadeOutMusic = () => {
    if (!backgroundMusic) return
    
    const fadeOutDuration = 500 // 500ms淡出时间
    const fadeOutSteps = 20
    const volumeStep = backgroundMusic.volume / fadeOutSteps
    const stepInterval = fadeOutDuration / fadeOutSteps
    
    let currentStep = 0
    const fadeOutTimer = setInterval(() => {
      currentStep++
      if (backgroundMusic) {
        backgroundMusic.volume = Math.max(0, backgroundMusic.volume - volumeStep)
      }
      
      if (currentStep >= fadeOutSteps) {
        clearInterval(fadeOutTimer)
        // 淡出完成后停止音乐
        stopBackgroundMusic()
      }
    }, stepInterval)
  }
  
  // 淡入音乐效果
  const fadeInMusic = () => {
    if (!backgroundMusic) return
    
    const fadeInDuration = 300 // 300ms淡入时间
    const fadeInSteps = 15
    const volumeStep = musicVolume.value / fadeInSteps
    const stepInterval = fadeInDuration / fadeInSteps
    
    // 从0音量开始
    backgroundMusic.volume = 0
    
    let currentStep = 0
    const fadeInTimer = setInterval(() => {
      currentStep++
      if (backgroundMusic) {
        backgroundMusic.volume = Math.min(musicVolume.value, backgroundMusic.volume + volumeStep)
      }
      
      if (currentStep >= fadeInSteps) {
        clearInterval(fadeInTimer)
        // 淡入完成后设置为目标音量
        if (backgroundMusic) {
          backgroundMusic.volume = musicVolume.value
        }
      }
    }, stepInterval)
  }
  
  // 切换音效开关
  const toggleSound = () => {
    isSoundEnabled.value = !isSoundEnabled.value
    localStorage.setItem('soundEnabled', JSON.stringify(isSoundEnabled.value))
    console.log('🔊 音效开关:', isSoundEnabled.value ? '开启' : '关闭')
  }
  
  // 设置音乐音量
  const setMusicVolume = (volume) => {
    musicVolume.value = Math.max(0, Math.min(1, volume))
    if (backgroundMusic) {
      backgroundMusic.volume = musicVolume.value
    }
    localStorage.setItem('musicVolume', musicVolume.value.toString())
  }
  
  // 设置音效音量
  const setSoundVolume = (volume) => {
    soundVolume.value = Math.max(0, Math.min(1, volume))
    localStorage.setItem('soundVolume', soundVolume.value.toString())
  }
  
  // 播放音效
  const playSound = (soundSrc) => {
    if (!isSoundEnabled.value || !soundSrc) return
    
    const sound = new Audio(soundSrc)
    sound.volume = soundVolume.value
    sound.play().catch(error => {
      console.warn('音效播放失败:', error)
    })
  }
  
  // 测试播放音乐
  const testPlayMusic = () => {
    console.log('🎵 测试播放音乐...')
    if (currentMusicSrc) {
      playBackgroundMusic(currentMusicSrc)
    } else {
      // 如果没有当前音乐源，尝试播放默认音乐
      const defaultMusicSrc = '/audio/大厅背景音乐.mp3'
      console.log('🎵 使用默认音乐源:', defaultMusicSrc)
      playBackgroundMusic(defaultMusicSrc)
    }
  }
  
  // 清理资源
  const cleanup = () => {
    stopBackgroundMusic()
  }
  
  return {
    // 状态
    isMusicEnabled,
    isSoundEnabled,
    musicVolume,
    soundVolume,
    isPlaying,
    
    // 计算属性
    musicIcon,
    soundIcon,
    
    // 方法
    initAudio,
    playBackgroundMusic,
    stopBackgroundMusic,
    pauseBackgroundMusic,
    resumeBackgroundMusic,
    toggleMusic,
    toggleSound,
    setMusicVolume,
    setSoundVolume,
    playSound,
    testPlayMusic,
    cleanup
  }
})
